package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @desc: 读写文件工具类
 *
 * @className: ReadCodeUtil.java
 * @author: fuchen
 * @date: 2020年10月26日
 */
public class FileUtil {
	/**-------------------------------- 词法分析输入输出  -------------------------------------*/
	//源程序
	public static final String CF_INPUT = "lexer\\test.txt";
	//分词结果
	public static final String CF_OUTPUT = "lexer\\result.txt";
	
	
	/**-------------------------------- 语法分析输入输出  -------------------------------------*/
	//文法表达式
	public static final String YF_INPUT = "parser\\test.txt";
	//结果
	public static final String YF_OUTPUT = "parser\\result.txt";

		
	/**-------------------------------- 语义分析输入输出  -------------------------------------*/
	//源程序
	public static final String YY_INPUT = "semantic\\test.txt";
	//分词结果
	public static final String YY_OUTPUT = "semantic\\result.txt";
	
	//语法分析器使用的按行读取
	//key:表达式 value:反馈结果
	public static Map<String, String> expMap = new HashMap<>();
	
	/**
	 * 读取
	 * @return
	 * @throws IOException
	 */
	public static String readFile(String url) throws IOException {
		FileReader reader = new FileReader(url);
		BufferedReader bufferedReader = new BufferedReader(reader);

		StringBuilder stringBuilder = new StringBuilder();
		String line = null;
		while((line = bufferedReader.readLine()) != null) {
			expMap.put(line, "right");
			stringBuilder.append(line).append(System.lineSeparator());
		}
	
		if(bufferedReader != null) {
			bufferedReader.close();
		}
		if(reader != null)
			reader.close();
		return stringBuilder.delete(stringBuilder.lastIndexOf(System.lineSeparator()), stringBuilder.length()).toString();
	}
	
//	public static Map<String, String> readLineForMap(String url) throws FileNotFoundException {
//		FileReader reader = new FileReader(url);
//		BufferedReader bufferedReader = new BufferedReader(reader);
//		Map<String, String> map = new HashMap<>();
//		
//		return bufferedReader;
//	}
	
	//默认追加写
	public static void writeFile(String str, String url) {
		writeFile(str, url, true);	
	}
	
	public static void writeFile(String str, String url, boolean append) {
		FileWriter writer = null;
		BufferedWriter bufferedWriter = null;
		try {
			//可追加
			writer = new FileWriter(url, append);
			bufferedWriter = new BufferedWriter(writer);
			bufferedWriter.write(str + System.lineSeparator());
			bufferedWriter.flush();
			bufferedWriter.close();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedWriter != null)
					bufferedWriter.close();
				if (writer != null)
					writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}
